package com.hulk.dryad.manage.framework.datasource;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.hulk.dryad.manage.framework.tenant.TenantContextHolder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 根据租户号指定当前数据源
 * @author hulk
 * @date 2020/9/13
 *
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE+1)
public class DynamicDataSourceFilter extends GenericFilterBean {

	@Override
	@SneakyThrows
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
		//DynamicDataSourceContextHolder.clear();
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String tenantId = TenantContextHolder.getTenantId();
		DynamicDataSourceContextHolder.push(tenantId);
		filterChain.doFilter(request, response);
		DynamicDataSourceContextHolder.clear();
	}

}
